package model

import (
	"database/sql"
	"fmt"
	"strings"
	"time"

	"github.com/tal-tech/go-zero/core/stores/cache"
	"github.com/tal-tech/go-zero/core/stores/sqlc"
	"github.com/tal-tech/go-zero/core/stores/sqlx"
	"github.com/tal-tech/go-zero/core/stringx"
	"github.com/tal-tech/go-zero/tools/goctl/model/sql/builderx"
)

var (
	tbUserFieldNames          = builderx.RawFieldNames(&TbUser{})
	tbUserRows                = strings.Join(tbUserFieldNames, ",")
	tbUserRowsExpectAutoSet   = strings.Join(stringx.Remove(tbUserFieldNames, "`id`", "`create_time`", "`update_time`"), ",")
	tbUserRowsWithPlaceHolder = strings.Join(stringx.Remove(tbUserFieldNames, "`id`", "`create_time`", "`update_time`"), "=?,") + "=?"

	cacheTbUserIdPrefix     = "cache::tbUser:id:"
	cacheTbUserMobilePrefix = "cache::tbUser:mobile:"
	cacheTbUserNamePrefix   = "cache::tbUser:name:"
)

type (
	TbUserModel interface {
		Insert(data TbUser) (sql.Result, error)
		FindOne(id int64) (*TbUser, error)
		FindAll(page, limit int) (int64, []*TbUser, error)
		FindOneByMobile(mobile string) (*TbUser, error)
		FindOneByName(name string) (*TbUser, error)
		Update(data TbUser) error
		Delete(id int64) error
	}

	defaultTbUserModel struct {
		sqlc.CachedConn
		table string
	}

	TbUser struct {
		Id         int64     `db:"id"`
		Name       string    `db:"name"`     // 用户名
		Password   string    `db:"password"` // 密码
		Mobile     string    `db:"mobile"`   // 手机号
		Citycode   string    `db:"citycode"` // 城市代码
		Tenant     int64     `db:"tenant"`   // 租户ID
		CreateTime time.Time `db:"create_time"`
		UpdateTime time.Time `db:"update_time"`
	}
)

func NewTbUserModel(conn sqlx.SqlConn, c cache.CacheConf) TbUserModel {
	return &defaultTbUserModel{
		CachedConn: sqlc.NewConn(conn, c),
		table:      "`tb_user`",
	}
}

func (m *defaultTbUserModel) Insert(data TbUser) (sql.Result, error) {
	tbUserMobileKey := fmt.Sprintf("%s%v", cacheTbUserMobilePrefix, data.Mobile)
	tbUserNameKey := fmt.Sprintf("%s%v", cacheTbUserNamePrefix, data.Name)
	ret, err := m.Exec(func(conn sqlx.SqlConn) (result sql.Result, err error) {
		query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?)", m.table, tbUserRowsExpectAutoSet)
		return conn.Exec(query, data.Name, data.Password, data.Mobile, data.Citycode, data.Tenant)
	}, tbUserMobileKey, tbUserNameKey)
	return ret, err
}

func (m *defaultTbUserModel) FindOne(id int64) (*TbUser, error) {
	tbUserIdKey := fmt.Sprintf("%s%v", cacheTbUserIdPrefix, id)
	var resp TbUser
	err := m.QueryRow(&resp, tbUserIdKey, func(conn sqlx.SqlConn, v interface{}) error {
		query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", tbUserRows, m.table)
		return conn.QueryRow(v, query, id)
	})
	switch err {
	case nil:
		return &resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

func (m *defaultTbUserModel) FindAll(page, limit int) (int64, []*TbUser, error) {
	var resp []*TbUser
	var count int64

	queryCount := fmt.Sprintf("select count(1) as count from %s ", m.table)
	err := m.CachedConn.QueryRowNoCache(&count, queryCount)
	if err != nil {
		return 0, nil, err
	}
	query := fmt.Sprintf("select * from %s limit ?,?", m.table)
	err = m.CachedConn.QueryRowsNoCache(&resp, query, (page-1)*limit, limit)
	switch err {
	case nil:
		return count, resp, nil
	case sqlc.ErrNotFound:
		return 0, nil, ErrNotFound
	default:
		return 0, nil, err
	}
}

func (m *defaultTbUserModel) FindOneByMobile(mobile string) (*TbUser, error) {
	tbUserMobileKey := fmt.Sprintf("%s%v", cacheTbUserMobilePrefix, mobile)
	var resp TbUser
	err := m.QueryRowIndex(&resp, tbUserMobileKey, m.formatPrimary, func(conn sqlx.SqlConn, v interface{}) (i interface{}, e error) {
		query := fmt.Sprintf("select %s from %s where `mobile` = ? limit 1", tbUserRows, m.table)
		if err := conn.QueryRow(&resp, query, mobile); err != nil {
			return nil, err
		}
		return resp.Id, nil
	}, m.queryPrimary)
	switch err {
	case nil:
		return &resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

func (m *defaultTbUserModel) FindOneByName(name string) (*TbUser, error) {
	tbUserNameKey := fmt.Sprintf("%s%v", cacheTbUserNamePrefix, name)
	var resp TbUser
	err := m.QueryRowIndex(&resp, tbUserNameKey, m.formatPrimary, func(conn sqlx.SqlConn, v interface{}) (i interface{}, e error) {
		query := fmt.Sprintf("select %s from %s where `name` = ? limit 1", tbUserRows, m.table)
		if err := conn.QueryRow(&resp, query, name); err != nil {
			return nil, err
		}
		return resp.Id, nil
	}, m.queryPrimary)
	switch err {
	case nil:
		return &resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

func (m *defaultTbUserModel) Update(data TbUser) error {
	tbUserNameKey := fmt.Sprintf("%s%v", cacheTbUserNamePrefix, data.Name)
	tbUserIdKey := fmt.Sprintf("%s%v", cacheTbUserIdPrefix, data.Id)
	tbUserMobileKey := fmt.Sprintf("%s%v", cacheTbUserMobilePrefix, data.Mobile)
	_, err := m.Exec(func(conn sqlx.SqlConn) (result sql.Result, err error) {
		query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, tbUserRowsWithPlaceHolder)
		return conn.Exec(query, data.Name, data.Password, data.Mobile, data.Citycode, data.Tenant, data.Id)
	}, tbUserIdKey, tbUserMobileKey, tbUserNameKey)
	return err
}

func (m *defaultTbUserModel) Delete(id int64) error {
	data, err := m.FindOne(id)
	if err != nil {
		return err
	}

	tbUserNameKey := fmt.Sprintf("%s%v", cacheTbUserNamePrefix, data.Name)
	tbUserIdKey := fmt.Sprintf("%s%v", cacheTbUserIdPrefix, id)
	tbUserMobileKey := fmt.Sprintf("%s%v", cacheTbUserMobilePrefix, data.Mobile)
	_, err = m.Exec(func(conn sqlx.SqlConn) (result sql.Result, err error) {
		query := fmt.Sprintf("delete from %s where `id` = ?", m.table)
		return conn.Exec(query, id)
	}, tbUserIdKey, tbUserMobileKey, tbUserNameKey)
	return err
}

func (m *defaultTbUserModel) formatPrimary(primary interface{}) string {
	return fmt.Sprintf("%s%v", cacheTbUserIdPrefix, primary)
}

func (m *defaultTbUserModel) queryPrimary(conn sqlx.SqlConn, v, primary interface{}) error {
	query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", tbUserRows, m.table)
	return conn.QueryRow(v, query, primary)
}
